from django.shortcuts import render,HttpResponseRedirect, HttpResponse
from django.http import JsonResponse
from django.views.generic import View
from django.utils.html import mark_safe
from django.db.models import Q
from django.core.paginator import *
from .models import *
import time, json

from utils.constant import ACTIVED
from utils.view import get_params
from utils.salt import get_salt_token, get_minion, del_minion, add_minion
from task import salt_command

# Create your views here.


class SaltMinionsView(View):
    def get(self, request):
        if request.user.is_authenticated():
            search, start, end, entry, num = get_params(request)
            token = get_salt_token()
            result = get_minion(token)
            context = {'saltminion': ACTIVED, 'salt': ACTIVED, 'table_class': mark_safe('table table-bordered'),'entry': entry}
            minions = list()
            for r in result['minion']:
                minion = dict()
                minion['id'] = r
                minion['online'] = 1
                minions.append(minion)
            for r in result['minions_pre']:
                minion = dict()
                minion['id'] = r
                minion['online'] = 0
                minions.append(minion)
            if search:
                temp = list()
                for minion in minions:
                    if search in minion['id']:
                        temp.append(minion)
                    if search == minion['online']:
                        temp.append(minion)
                minions = temp
            paginator = Paginator(minions, entry)
            minions = paginator.page(num)
            context['objects'] = minions

            return render(request, 'SlatStack/saltminions.html', context=context)
        else:
            return HttpResponseRedirect('/')

    def post(self, request):
        if request.user.is_authenticated():
            method = request.POST.get('method')
            minion_id = request.POST.get('id')
            print minion_id
            minions = list()
            minions.append(minion_id)
            token = get_salt_token()
            if method == 'del':
                res = del_minion(token,minions)
                return JsonResponse({'status': res})
            elif method == 'add':
                res = add_minion(token,minions)
                print res
                return JsonResponse({'status': res})
        else:HttpResponse(status=403)



class ManageSlatCommandView(View):
    def get(self, request):
        if request.user.is_authenticated():
            search ,start, end, entry, num = get_params(request)
            context = {'saltcommand': ACTIVED, 'salt': ACTIVED, 'table_class': mark_safe('table table-bordered'), 'search': '', 'entry': entry}
            if not search:
                commands = SaltCommand.objects.all()
            else:
                commands = SaltCommand.objects.filter(Q(name__icontains=search) |
                                         Q(type=search) |
                                         Q(description__icontains=search)).all()
                context['search'] = context['search'] + 'top-search=' + search
                context['last_search'] = search
            if not commands.exists():
                return render(request, 'SlatStack/saltcmds.html', context=context)
            if start:
                commands = commands.filter(add_time__gte=start)
                context['search'] = context['search'] + 'start=' + start + '&'
                context['start'] = start
            if  end:
                time_end = end + " 23:59:59"
                commands = commands.filter(add_time__lte=time_end)
                context['search'] = context['search'] + 'end=' + end + '&'
                context['end'] = end
            paginator = Paginator(commands, entry)
            commands = paginator.page(num)
            context['objects'] = commands
            return render(request, 'SlatStack/saltcmds.html', context=context)
        else:
            return HttpResponseRedirect('/')


class AddSaltModelView(View):
    def get(self, request):
        if request.user.is_authenticated():
            cmd_id = cmd_id = request.GET.get('id')
            context = {'saltcommand': ACTIVED, 'salt': ACTIVED}
            if cmd_id:
                s = SaltCommand.objects.get(id=cmd_id)
                context['cmd'] = s
            return render(request, 'SlatStack/addsaltmodel.html', context=context)
        else:
            return HttpResponseRedirect('/')

    def post(self, request):
        if request.user.is_authenticated():
            name = request.POST.get('name')
            cmd_id = request.POST.get('cmd_id')
            cmd = request.POST.get('cmd')
            args = request.POST.get('args')
            description = request.POST.get('description')
            try:
                if cmd_id:
                    cmd_id = int(cmd_id)
                    scmd = SaltCommand.objects.get(id=cmd_id)
                    scmd.name = name
                    scmd.cmd = cmd
                    scmd.args = args
                    scmd.type = 4
                    scmd.description = description
                else:
                    scmd = SaltCommand(name=name, cmd=cmd, type=4, description=description, args=args)
                scmd.save()
            except Exception as e:
                return  JsonResponse({'status': 0, 'msg': e.message})
            return JsonResponse({'status': 1})
        else:
            return HttpResponse(status=403)


class AddShellView(View):
    def get(self, request):
        if request.user.is_authenticated():
            cmd_id = request.GET.get('id')
            context = {'saltcommand': ACTIVED, 'salt': ACTIVED}
            if cmd_id:
                s =SaltCommand.objects.get(id=cmd_id)
                context['cmd'] = s
            return render(request, 'SlatStack/addsaltshell.html', context=context)
        else:
            return HttpResponseRedirect('/')

    def post(self, request):
        if request.user.is_authenticated():
            name = request.POST.get('name')
            cmd_id = request.POST.get('cmd_id')
            context = request.POST.get('context')
            description = request.POST.get('description')
            print description
            try:
                if cmd_id:
                    scmd = SaltCommand.objects.get(id=cmd_id)
                    scmd.name = name
                    scmd.context = context
                    scmd.type = 1
                    scmd.description = description
                else:
                    scmd =SaltCommand(name=name, context=context, type=1, description=description)
                scmd.save()
            except Exception as e:
                return  JsonResponse({'status': 0, 'msg': e.message})
            return JsonResponse({'status': 1})
        else:
            return HttpResponse(status=403)


def del_salt_cmd(request):
    if request.user.is_authenticated():
        cmd_id = request.POST.get('cmd_id')
        try:
            SaltCommand.objects.get(id=cmd_id).delete()
        except Exception as e:
            return JsonResponse({'status': 0, 'msg': e.message})
        return JsonResponse({'status': 1})
    else:
        return HttpResponse(status=403)


class ExecSaltView(View):
    def get(self, request):
        cmd_id = request.GET.get('cmd_id')
        token = get_salt_token()
        result = get_minion(token)
        minions = list()
        for r in result['minion']:
            minions.append(r)
        context = {'saltcommand': ACTIVED, 'salt': ACTIVED, 'minions': minions, 'cmd_id': cmd_id}
        return render(request, 'SlatStack/execsalt.html', context=context)

    def post(self, request):
        minions = json.loads(request.POST.get('minions'))
        cmd_id = request.POST.get('cmd_id')
        cmd = SaltCommand.objects.get(id=cmd_id)
        print type(minions)
        token = get_salt_token()
        if cmd.type == 0:
            salt_command(token, minions, cmd.context, cmd_id, request.user.id)
        return JsonResponse({'status': 1})
